package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"sz2/C/rpc/model/mysql"
	"sz2/C/rpc/pkg"

	"sz2/C/rpc/good"
	"sz2/C/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderGoodsLogic {
	return &OrderGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderGoodsLogic) OrderGoods(in *good.OrderGoodsRequest) (*good.OrderGoodsResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.Show(int(in.GoodsId))
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if g.ID == 0 {
		fmt.Println("商品不存在")
	}
	if in.Num > int64(g.GoodsStock) {
		return nil, fmt.Errorf("商品库存不足")
	}
	newString := uuid.NewString()
	amount := float64(in.Num) * g.GoodsPrice
	o := mysql.Order{
		UserId:  int(in.UserId),
		GoodId:  int(in.GoodsId),
		OrderSn: newString,
		Amount:  amount,
		PayType: int(in.Payment),
		Status:  1,
	}
	err = o.Create()
	if err != nil {
		return nil, fmt.Errorf("添加失败")
	}
	sprintf := fmt.Sprintf("%f", o.Amount)
	fmt.Println(o.Amount)
	pay := pkg.ALiPay(sprintf)
	return &good.OrderGoodsResponse{Order: pay}, nil
}
